﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.Common;
using System.Drawing;
//using System.Linq;
//using System.Text;
using System.Windows.Forms;
using System.Configuration;
//using System.Data.SqlClient;
using ECS.DAL;
using ECS.DAL.Entity;
using ECS.DAL.Component;
using ECS.Framework;
using ECS.BLL.Entity;
using ECS.BLL.Component;

using AutoUpdaterDotNET;

namespace E_ICS.Main
{
    public partial class frmLogin : Form
    {
        #region private properties
        //DataSet dataset = null;
        //SqlConnection sqlCon = new SqlConnection(ConfigurationManager.ConnectionStrings["con3"].ConnectionString);
        BackgroundWorker _worker = null;
        #endregion

        #region Form event
        
        public frmLogin()
        {
            InitializeComponent();
        }

        private void btnLogin_Click(object sender, EventArgs e)
        {
            try
            {
                if (ValidateInput())
                {
                    Login();
                }
            }
            catch (Exception ex)
            {
                CommonMessageBox.ShowMessageError(ex);
            }
            
        }
        private void btnCancel_Click(object sender, EventArgs e)
        {
            try
            {
                this.Close();
            }
            catch (Exception ex)
            {
                CommonMessageBox.ShowMessageError(ex);
            }
            
        }
        private void frmLogin_Load(object sender, EventArgs e)
        {
            try
            {
                lblVersion.Text = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString();
                _worker = new BackgroundWorker();
                _worker.DoWork += new DoWorkEventHandler(worker_DoWork);
                _worker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(worker_RunWorkerCompleted);
                _worker.WorkerSupportsCancellation = true;
                _worker.RunWorkerAsync();
                //CheckVersion();
            }
            catch (Exception ex)
            {
                CommonMessageBox.ShowMessageError(ex);
            }
        }

        private void worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            try
            {
                if (e.Error != null)
                {
                    CommonMessageBox.ShowMessageError(e.Error);
                }
            }
            catch (Exception ex)
            {
                CommonMessageBox.ShowMessageError(ex);
            }
            
        }

        private void worker_DoWork(object sender, DoWorkEventArgs e)
        {
            CheckVersion();
        }

        private void password_KeyPress(object sender, KeyPressEventArgs e)
        {
            try
            {
                if (e.KeyChar == (char)Keys.Enter)
                {
                    Login();
                }
            }
            catch (Exception ex)
            {
               CommonMessageBox.ShowMessageError(ex);
            }
        }
        private void txtUserId_KeyPress(object sender, KeyPressEventArgs e)
        {
            try
            {
                if (e.KeyChar == (char)Keys.Enter)
                {
                    password.Focus();
                }
            }
            catch (Exception ex)
            {
                CommonMessageBox.ShowMessageError(ex);
            }
        }
        private void frmLogin_Shown(object sender, EventArgs e)
        {
            try
            {
                //CheckVersion();
            }
            catch (Exception ex)
            {
                CommonMessageBox.ShowMessageError(ex);
            }

        }
        #endregion

        #region private methods
        private void CheckVersion()
        {
            string version = string.Empty;
            SearchInfo search = new SearchInfo();
            version = search.GetApplicationVersion();
            if (version != GlobalVariable.version)
            {
                AutoUpdater.Start(ConfigurationManager.AppSettings["Autoupdate"]);
            }
            //try
            //{
            //    using (Entities entity = new Entities())
            //    {
            //        entity.Open();
            //        DbCommand cmd = entity.CreateCommand("Select app_version from t_com_application where app_id='EICS PC'");
            //        DbDataReader reader = cmd.ExecuteReader();
            //        DbDataAdapter ad = entity.CreateDataAdapter(cmd);
            //        if (reader.Read())
            //        {
            //            string version = reader["app_version"].ToString();
            //            if (version != GlobalVariable.version)
            //            {
            //                AutoUpdater.Start("http://10.8.9.67//WebAppPor01/update.xml");
            //            }
            //        }
            //    }
            //}
            //catch (Exception ex)
            //{

            //    CommonMessageBox.ShowMessageError(ex);
            //}
        }
        private bool ValidateInput()
        {
            bool result = true;
            if (string.IsNullOrEmpty(txtUserId.Text))
            {
                CommonMessageBox.ShowMessageWarning(CommonResourceString.GetResourceString(CommonResourceString.ConstantString.INVALID_USER_ID));
                txtUserId.Focus();
                result = false;
            }
            return result;
        }
        /// <summary>
        /// check user/password permission with appID and device name
        /// </summary>
        private void Login()
        {
            string appId = string.Empty;
            string device = GlobalVariable.Device;
            string ClearUserFlag = string.Empty;
            string appVersion = GlobalVariable.version;
            //string device = ConfigurationManager.AppSettings["device"];
            //string appVersion = ConfigurationManager.AppSettings["version"];
            try
            {
                appId = ConfigurationManager.AppSettings["appID"];
                ClearUserFlag = ConfigurationManager.AppSettings["userflag"];
                UserAuthenticateComponent authen = new UserAuthenticateComponent();
                UserAuthenticate user = authen.GetUserAuthentication(txtUserId.Text, password.Text, appId, device, ClearUserFlag, appVersion);
                if (user != null)
                {
                    if (user.Status.Equals("PASS"))
                    {
                        SearchInfo searchInfo = new SearchInfo();
                        GlobalVariable.userName = txtUserId.Text;
                        GlobalVariable.user = user;
                        GlobalVariable.user.UserName = txtUserId.Text;
                        GlobalVariable.user.ApplicationID = appId;
                        GlobalVariable.user.Device = device;
                        GlobalVariable.user.ClearUserFlag = ClearUserFlag;
                        GlobalVariable.user.Version = appVersion;
                        GlobalVariable.scaleID = searchInfo.GetScaleId(GlobalVariable.user.Device);
                        GlobalVariable.fbl_fltNO = searchInfo.getFBLFlihtNo(GlobalVariable.user.Device);
                        //getScaleID(GlobalVariable.user.Device);
                       // getFBLfltNO(GlobalVariable.user.Device);
                        this.Visible = false;
                        this.Enabled = false;
                        Main.frmMain2 t = new Main.frmMain2();
                        t.Show();
                    }
                    else
                    {
                        CommonMessageBox.ShowMessageInfo(user.Message);
                    }
                }
            }
            catch (Exception ex)
            {
                CommonMessageBox.ShowMessageError(ex);
            }
        }

        private void frmLogin_FormClosing(object sender, FormClosingEventArgs e)
        {
            try
            {
                if (_worker.IsBusy)
                {
                    _worker.CancelAsync();
                }
                _worker.Dispose();
            }
            catch (Exception ex)
            {
                CommonMessageBox.ShowMessageError(ex);
            }
        }

        
        //private void getScaleID(string device)
        //{
        //    try
        //    {

        //        SqlCommand cmd = new SqlCommand("select setting_value_string from t_eics_setup where setting_name = 'SCALE ID' and station_id = @stationID", sqlCon);
        //        cmd.Parameters.AddWithValue("stationID", device);
        //        SqlDataAdapter DA = new SqlDataAdapter(cmd);
        //        sqlCon.Open();
        //        SqlDataReader reader3 = cmd.ExecuteReader();
        //        if (reader3.Read())
        //        {
        //            GlobalVariable.scaleID = reader3["setting_value_string"].ToString();
        //        }
        //        else
        //        {
        //            sqlCon.Close();
        //        }
                
        //    }
        //    catch
        //    {

        //        throw;
        //    }
        //    finally
        //    {
        //        if (sqlCon != null && sqlCon.State == ConnectionState.Open)
        //        {
        //            sqlCon.Close();
        //        }
        //    }
        //}
        //private void getFBLfltNO(string device)
        //{
        //    try
        //    {
        //        SqlCommand cmd = new SqlCommand("select setting_value_string from t_eics_setup where setting_name = 'FBL_FLT_NO' and station_id = @stationID", sqlCon);
        //        cmd.Parameters.AddWithValue("stationID", device);
        //        SqlDataAdapter DA = new SqlDataAdapter(cmd);
        //        sqlCon.Open();
        //        SqlDataReader reader3 = cmd.ExecuteReader();
        //        if (reader3.Read())
        //        {
        //            GlobalVariable.fbl_fltNO = reader3["setting_value_string"].ToString();
        //        }
        //        else
        //        {
        //            sqlCon.Close();
        //        }
        //    }
        //    catch (Exception)
        //    {
                
        //        throw;
        //    }
        //    finally
        //    {
        //        if (sqlCon != null && sqlCon.State == ConnectionState.Open)
        //        {
        //            sqlCon.Close();
        //        }
        //    }
        //}
        #endregion

        //SqlCommand cmd = new SqlCommand();
        //cmd.CommandText = "usp_AuthenticateUser";
        //cmd.CommandType = CommandType.StoredProcedure;
        //cmd.Connection = sqlCon;
        //cmd.Parameters.AddWithValue("@in_vchUserID", userID.Text);
        //cmd.Parameters.AddWithValue("@in_vchPassword", password.Text);
        //cmd.Parameters.AddWithValue("@in_vchApplicationID", appId);
        //cmd.Parameters.AddWithValue("@in_vchDevice", device);
        //cmd.Parameters.AddWithValue("@in_vchClearUserFlag", ClearUserFlag);
        //cmd.Parameters.AddWithValue("@in_vchInterfaceVersionNumber", appVersion);
        //try
        //{
        //    sqlCon.Open();
        //    SqlDataAdapter da = new SqlDataAdapter(cmd);
        //    dataset = new DataSet();
        //    da.Fill(dataset, "testlogin");
        //    string status = dataset.Tables[0].Rows[0]["Column1"].ToString();
        //    if (status == "PASS")
        //    {
        //        GlobalVariable.userName = userID.Text;
        //        Main.frmMain2 t = new Main.frmMain2();
        //        t.Show();
        //        this.Visible = false;
        //        this.Enabled = false;
        //    }
        //    else
        //    {
        //        //string error_code = dataset.Tables[0].Rows[0]["Column2"].ToString();
        //        string msg = dataset.Tables[0].Rows[0]["Column3"].ToString();
        //        MessageBox.Show(msg);
        //    }
        //    sqlCon.Close();
        //}
        //catch (Exception objEx)
        //{
        //    string str = objEx.Message;
        //    MessageBox.Show(str);
        //}
    }
}
